<template>
  <div class="container">
    <!-- 气象数据标题 -->
    <div class="container-header">
      <div class="container-header-text">站点气象数据</div>
      <el-date-picker
        v-model="selectedTime"
        type="datetime"
        placeholder="选择时间"
        @change="handleTimeChange"
        :disabled-date="disabledDate"
      />
    </div>
    <!-- 数据展示 -->
    <div class="grid-container">
      <div class="grid-item" v-for="(item, index) in gridData" :key="index">
        <el-icon :style="`color: ${item.iconColor}; font-size: 4vh;`">
          <component :is="item.icon" />
        </el-icon>
        <div class="grid-item-description">{{ item.description }}</div>
        <div class="grid-item-data">
          <div class="grid-item-data-value">
            {{ item.currentValue[1] }}
          </div>
          <div class="grid-item-data-unit">
            {{ item.unit }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, markRaw, shallowRef } from 'vue';
import { ElIcon, ElDatePicker } from 'element-plus';
import { MostlyCloudy, Sunny, WindPower, DCaret, TrendCharts, Key, Pouring, Filter, Histogram } from '@element-plus/icons-vue';
import { findMeteorologyByUserSelectSingleTimeStamp } from '@/api/meteorology.js';
import { findLatestMeteorology } from '@/api/meteorology.js';

const selectedTime = ref(null);

// 定义气象数据展示的数据
const gridData = reactive([
  { description: '空气温度',unit: '(°C)', icon: markRaw(Key), iconColor: "#ff793f", currentValue: ["", 0] },
  { description: '向下短波辐射',unit: '(W/m²)', icon: markRaw(TrendCharts), iconColor: '#ff9f1a', currentValue: ["良好", 0] },
  { description: '光合有效辐射',unit: '(μmol/m²/s)', icon: markRaw(Sunny), iconColor: '#FEF201', currentValue: ["", 0] },
  { description: '降雨量',unit: '(mm)', icon: markRaw(Pouring), iconColor: '#1CB0BC', currentValue: ["", 0] },
  { description: '土壤含水量(5cm)',unit: '(%)', icon: markRaw(Filter), iconColor: '#1CB0BC', currentValue: ["", 0] },
  { description: '水位值',unit: '(cm)', icon: markRaw(Histogram), iconColor: '#2ecc71', currentValue: ["", 0] }
]);

// 更新数据
const updateCurrentShowDataByUserSelectSingleTimeStamp = async () => {
  try {
    const result = await findMeteorologyByUserSelectSingleTimeStamp(selectedTime.value);

    console.log(result.data);
    if (result.data == null) {
      gridData.forEach(item => item.currentValue = ["", 111]);
    }else {
      const meteorologyData = result.data;
      gridData[0].currentValue = ["", meteorologyData.taAvg];
      gridData[1].currentValue = ["", meteorologyData.drAvg];
      gridData[2].currentValue = ["", meteorologyData.parAvg];
      gridData[3].currentValue = ["", meteorologyData.rainTot];
      gridData[4].currentValue = ["", (meteorologyData.vmc5cmAvg * 100).toFixed(2)];
      gridData[5].currentValue = ["", meteorologyData.waterLevel];
    }
  } catch (err) {
    gridData.forEach(item => item.currentValue = ["", 999]);
    console.error('获取气象数据失败:', err);
  }
};

// 时间选择器的配置 目前未生效
// const pickerOptions = reactive({
//   selectableRange: ['00:00:00', '23:59:59'], // 可选时间范围
//   step: "00:30", // 设置时间选择器的步长为每半小时
// });

// 更新时间后，更新数据
const handleTimeChange = () => {
  updateCurrentShowDataByUserSelectSingleTimeStamp();
};

// 数据库中拥有数据的最新时间
// const LastedTimeByData = ref(null);

// 禁用时间选择器的时间
// const disabledDate = (time) => {
//   return LastedTimeByData.value ? time.getTime() > LastedTimeByData.value.getTime() : false;
// };

// 禁用时间选择器的时间，不能超过当前时间
const disabledDate = (time) => {
  return time.getTime() > new Date().getTime();
};

onMounted(() => {
  // 获取当前数据库中最新的数据
  findLatestMeteorology().then(result => {
    if (result.data == null) {
      gridData.forEach(item => item.currentValue = ["", 111]);
    }else {
      console.log(result.data)
      // 更新时间选择器的时间
      selectedTime.value = new Date(result.data.timestamp);
      // 更新存在数据的最新的时间
      // LastedTimeByData.value = new Date(result.data.timestamp);

      // 设定时间选择器规整，selectedTime后的的时间不能选择

      const meteorologyData = result.data;
      gridData[0].currentValue = ["", meteorologyData.taAvg];
      gridData[1].currentValue = ["", meteorologyData.drAvg];
      gridData[2].currentValue = ["", meteorologyData.parAvg];
      gridData[3].currentValue = ["", meteorologyData.rainTot];
      gridData[4].currentValue = ["", (meteorologyData.vmc5cmAvg * 100).toFixed(2)];
      gridData[5].currentValue = ["", meteorologyData.waterLevel];
    }
  }).catch(err => {
    gridData.forEach(item => item.currentValue = ["", 999]);
    console.error('获取气象数据失败:', err);
  });

});
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  .container-header {
    height: 20%;
    padding-top: 1%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    font-size: 3vh;
    font-weight: bold;
    color: #ecf0f1;
    .container-header-text {
      font-size: 2.3vh;
      color: #1e90ff;
    }
  }

  .grid-container {
    height: 80%;
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 0;
    flex-grow: 1;
    margin: 0 2% 2% auto;

    .grid-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 1.8vh;
      color: #1e90ff;
      background: radial-gradient(circle, rgba(28, 176, 188, 0.05), rgba(28, 176, 188, 0.1));
      margin: 0 5% 2% 5%;
      font-weight: bold;

      .grid-item-description {
        margin-top: 2%;
      }

      .grid-item-data {
        display: flex;
        .grid-item-data-value {
          font-size: 1.5vh;
          color: #ecf0f1;
          margin-right: 3%;
        }
        .grid-item-data-unit {
          font-size: 1.5vh;
          color: #bbbebe;
        }
        padding-top: 1%;
      }
    }
  }
}
</style>